package com.baizhi.service.impl;

import com.baizhi.dao.StudentDao;
import com.baizhi.Student;
import com.baizhi.service.StudentService;
import com.baizhi.util.MyBatisUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentServiceImpl implements StudentService {
    @Override
    public List<Student> findAll() {
        SqlSession session = MyBatisUtils.openSession();
        List<Student> students = null;
        try {
            StudentDao mapper = session.getMapper(StudentDao.class);
            students = mapper.selectList(null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtils.close(session);
        }
        return  students;
    }

    @Override
    public boolean insert(Student u) {
        SqlSession session=MyBatisUtils.openSession();
        try {
            StudentDao mapper = session.getMapper(StudentDao.class);
            mapper.insert(u);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw  new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
        return true;
    }

    @Override
    public PageInfo<Student> page(int pageIndex, int pageSize) {
        SqlSession session=MyBatisUtils.openSession();
        List<Student> allStudent=null;
        try {
            PageHelper.startPage(pageIndex,pageSize);
            StudentDao mapper = session.getMapper(StudentDao.class);
            allStudent = mapper.findAllStudent();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtils.close(session);
        }
            PageInfo<Student> pageInfo=new PageInfo<>(allStudent);
        return pageInfo;
    }

    @Override
    public List<Student> findShow() {
        SqlSession session=MyBatisUtils.openSession();
        List<Student> students=null;
        try {
            StudentDao mapper = session.getMapper(StudentDao.class);
            students = mapper.selectList(null);
        } catch (Exception e) {
            throw  new RuntimeException(e);
        } finally {
            session.close();
        }
        return students;
    }

}
